package com.wangbaokang.duanxin;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AlertDialog;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.wangbaokang.duanxin.db.DbUtils;
import com.wangbaokang.duanxin.tools.MyConstants;
import com.wangbaokang.duanxin.tools.MyQueryHandler;
import com.wangbaokang.duanxin.tools.Tools;

import java.util.HashSet;

/**
 * Created by wangbaokang on 2016-08-18.
 */
public class ConversationUI extends Activity implements AdapterView.OnItemClickListener {

    private ListView listView;
    private Button btnNewMassage;
    private Button btnSelectAll;
    private Button btnSelectNull;
    private Button btnDeleteMessage;

    private boolean isEditState = false;

    private MyListAdapter adapter;

    private Context ctx;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conversation);

        this.ctx = this;

        init();
        flushState();
        prepareDate();
    }

    /**
     * 要查询的列
     */
    private String[] projection= new String[]{
            "sms.body AS snippet",
            "sms.thread_id AS _id",
            "groups.msg_count AS msg_count",
            "address as address",
            "date as date"
    };

    /**
     * 查询结果所在列的索引值
     */
    private final int INDEX_BODY = 0;
    private final int INDEX_THREAD_ID = 1;
    private final int INDEX_MSG_COUNT = 2;
    private final int INDEX_ADDRESS = 3;
    private final int INDEX_DATE = 4;

    /**
     * 给listView准备数据
     */
    private void prepareDate(){
        /**
         *查询数据库 如果数据过多了 会造成ANR异常 所以一般会开启子线程 然后用handler将数据回传
         */
        MyQueryHandler queryHandler = new MyQueryHandler(getContentResolver());
        queryHandler.startQuery(1, adapter, MyConstants.URI_CONVERSATION, projection, null, null, " date desc");


    }

    private void init(){
        btnNewMassage = (Button) findViewById(R.id.btn_new_message_conversation);
        btnSelectAll = (Button) findViewById(R.id.btn_select_all_conversation);
        btnSelectNull = (Button) findViewById(R.id.btn_select_null_conversation);
        btnDeleteMessage = (Button) findViewById(R.id.btn_delete_message_conversation);
        listView = (ListView) findViewById(R.id.lv_conversation);
        adapter = new MyListAdapter(this, null);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(this);
        selectItemSet = new HashSet<Integer>();
    }


    private void flushState(){

        if(isEditState){
            btnNewMassage.setVisibility(View.GONE);
            btnSelectAll.setVisibility(View.VISIBLE);
            btnSelectNull.setVisibility(View.VISIBLE);
            btnDeleteMessage.setVisibility(View.VISIBLE);
        }else{
            btnNewMassage.setVisibility(View.VISIBLE);
            btnSelectAll.setVisibility(View.GONE);
            btnSelectNull.setVisibility(View.GONE);
            btnDeleteMessage.setVisibility(View.GONE);
        }

        if(selectItemSet.size() == 0){
            //是空的
            //让不选 和删除按钮失效
            btnSelectNull.setEnabled(false);
            btnDeleteMessage.setEnabled(false);
        }else{
            btnSelectNull.setEnabled(true);
            btnDeleteMessage.setEnabled(true);
        }

        if(selectItemSet.size() == adapter.getCount()){
            btnSelectAll.setEnabled(false);
        }else{
            btnSelectAll.setEnabled(true);
        }

    }

    /**
     * 相应listView的条目点击事件
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        //通过adapter 获得cursor对象
        Cursor cursor = adapter.getCursor();
        //讲cursor移动到相应的位置
        cursor.moveToPosition(position);
        //取得相应位置的会话ID
        int threadId = cursor.getInt(INDEX_THREAD_ID);
        if(isEditState){//在编辑状态下 执行

            //判断集合中是否有对应的会话ID
            if(selectItemSet.contains(threadId)){//如果有 删除掉对应会话ID
                selectItemSet.remove(threadId);
            }else{//如果没有添加对应的会话Id
                selectItemSet.add(threadId);
            }

            //刷新listView
            adapter.notifyDataSetChanged();
            //刷新
            flushState();
        }else{
            //打开会话详情的activity
            //获得对应条目的电话号码
            String address = cursor.getString(INDEX_ADDRESS);
            Intent intent = new Intent(this,ConversationDetail.class);
            intent.putExtra("address", address);//将当前条目对应的电话号码传递到对话详情页面
            startActivity(intent);
        }

    }

    class MyListAdapter extends CursorAdapter{

        public MyListAdapter(Context context, Cursor c) {
            super(context, c);
        }

        /**
         * 当contentView是null时  需要用户自己新建一个view 的时候调用
         * @param context
         * @param cursor
         * @param parent
         * @return
         */
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {

            View view = View.inflate(ctx, R.layout.list_item_conversation, null);

            ViewHolder vh = new ViewHolder();
            vh.face = (ImageView) view.findViewById(R.id.iv_face_list_item);
            vh.address = (TextView) view.findViewById(R.id.tv_address_list_item);
            vh.body = (TextView) view.findViewById(R.id.tv_body_list_item);
            vh.date = (TextView) view.findViewById(R.id.tv_date_list_item);
            vh.checkBox = (ImageView) view.findViewById(R.id.iv_checkbox_list_item);
            view.setTag(vh);
            return view;
        }

        /**
         * 为itemView绑定内容是调用
         * @param view   newView()的返回值
         * @param context
         * @param cursor
         */
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            ViewHolder vh = (ViewHolder) view.getTag();

            //短信内容
            vh.body.setText(cursor.getString(INDEX_BODY));

            //联系人 如果没有保存联系人 则显示号码
            String name = Tools.findNameByNumber(ctx, cursor.getString(INDEX_ADDRESS));
            if (name == null) {
                vh.address.setText(cursor.getString(INDEX_ADDRESS)+"("+cursor.getString(INDEX_MSG_COUNT)+")");
            }else {
                vh.address.setText(name+"("+cursor.getString(INDEX_MSG_COUNT)+")");
            }

            //时间显示 如果是当天显示具体小时 如果不是当天显示年月日
            long when = cursor.getLong(INDEX_DATE);
            String dataStr = "";
            if(DateUtils.isToday(when)){//是今天 格式化为小时
               dataStr = DateFormat.getTimeFormat(ctx).format(when);
            }else{//不是今天格式化为年月日
                dataStr = DateFormat.getDateFormat(ctx).format(when);
            }
            vh.date.setText(dataStr);

            /**
             * 根据电话号码查询联系人Id
             * 如果id=-1 表示没有此联系人 此时应设置一个默认的未知的联系人头像
             * 然后根据Id查询联系人头像 返回bitmap
             * 如果bitmap==null 表示此联系人没有设置头像 应设置一个默认的联系人头像
             * 如果不为空 设置为联系人头像
             */

            int id = Tools.findIdByNumber(ctx, cursor.getString(INDEX_ADDRESS));
            if (id == -1) {
                vh.face.setBackgroundResource(R.drawable.ic_unknow_contact_picture);
            }else {
                Bitmap bitmap = Tools.getFaceById(ctx, id+"");
                if (bitmap == null ) {
                    vh.face.setBackgroundResource(R.drawable.ic_contact_picture);
                }else {
                    vh.face.setBackgroundDrawable(new BitmapDrawable(bitmap));
                }

            }

            /**
             * 这是checkbox
             */
            if (isEditState) {//如果是编辑状态显示checkbox
                vh.checkBox.setVisibility(View.VISIBLE);

                //该条目对应的回话Id
                int threadId = cursor.getInt(INDEX_THREAD_ID);
                //判断集合之中是否有该条目对应的回话Id 如果有则是选中状态 没有则是没选中状态
                if(selectItemSet.contains(threadId)){
                    vh.checkBox.setEnabled(true);
                }else {
                    vh.checkBox.setEnabled(false);
                }

            }else {//否则隐藏
                vh.checkBox.setVisibility(View.GONE);
            }


        }
    }

    /**
     * 存储在编辑状态下选中的listView的条目
     */
    private HashSet<Integer> selectItemSet;

    class ViewHolder{
        public ImageView checkBox;
        public ImageView face;
        public TextView address;
        public TextView body;
        public TextView date;
    }

    private final int ID_SEARCH = 100;
    private final int ID_EDIT = 101;
    private final int ID_CANCEL_EDIT = 102;


    /**
     * 第一次点击menu按键是调用  用于创建 菜单选项
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add(0, ID_SEARCH, 0, "搜索");
        menu.add(0, ID_EDIT, 0, "编辑");
        menu.add(0, ID_CANCEL_EDIT, 0, "取消编辑");

        return true;
    }


    /**
     * 每次按menu按键是调用 做一些准备工作
     * @param menu
     * @return
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        if (isEditState) {
            menu.findItem(ID_EDIT).setVisible(false);
            menu.findItem(ID_EDIT).setVisible(false);
            menu.findItem(ID_CANCEL_EDIT).setVisible(true);
        } else {
            menu.findItem(ID_EDIT).setVisible(true);
            menu.findItem(ID_EDIT).setVisible(true);
            menu.findItem(ID_CANCEL_EDIT).setVisible(false);
        }

        return true;
    }

    /**
     * 当选择某一个菜单时调用
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case ID_SEARCH:

                //点击搜索菜单
                onSearchRequested();
                break;

            case ID_EDIT:

                isEditState = true;
                flushState();
                break;

            case ID_CANCEL_EDIT:

                isEditState = true;
                flushState();
                break;



        }




        return true;
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_delete_message_conversation:
                //删除按钮
                showConfirmDeleteDialog();
                break;
            case R.id.btn_new_message_conversation:
                //新建短信
//                startActivity(new Intent(this,NewMessageUI.class));


                break;
            case R.id.btn_select_all_conversation:
                //全选
                Cursor cursor = adapter.getCursor();
                //让cursor移到第一行的上一行
                cursor.moveToPosition(-1);
                while (cursor.moveToNext()) {
                    Integer threadId = cursor.getInt(INDEX_THREAD_ID);
                    selectItemSet.add(threadId);
                }
                flushState();
                adapter.notifyDataSetChanged();

                break;
            case R.id.btn_select_null_conversation:
                //不选
                selectItemSet.clear();
                flushState();
                adapter.notifyDataSetChanged();

                break;

            default:
                break;
        }

    }

    /**
     * 确认删除的对话框
     */
    private void showConfirmDeleteDialog() {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        adb.setTitle("确认");
        adb.setMessage("确认要删除选中的短信会话吗？");
        adb.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                showDeleteProgressDialog();
                //开启子线程，执行删除 的操作
                new Thread(new DeleteMessageRunnable()).start();
            }
        });
        adb.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //取消显示对话框
                dialog.dismiss();

            }
        });
        adb.show();
    }

    private ProgressDialog proDlg;
    /**
     * 显示删除的进度对话框
     */
    protected void showDeleteProgressDialog() {
        proDlg =new ProgressDialog(this);
        proDlg.setTitle("正在删除");
        //设置进度框为进度条样式
        proDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //设置进度条的最大值
        proDlg.setMax(selectItemSet.size());
        proDlg.setButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                isCancleDeleteMessage =true;
                proDlg.dismiss();

            }
        });
        //给进度对话框添加监听，当对话框关闭的时候，触发监听
        proDlg.setOnDismissListener(new DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                //设置编辑状态为false
                isEditState = false;

                flushState();

            }
        });
        proDlg.show();
    }

    /**
     * 是否取消删除
     */
    private boolean isCancleDeleteMessage = false;

    class DeleteMessageRunnable implements Runnable{

        @Override
        public void run() {

            //用增强for循环遍历 hashSet集合
            for(Integer threadId : selectItemSet){
                //体眠，不会抛异常
                SystemClock.sleep(1000);
                //判断 是否取消
                if(isCancleDeleteMessage){
                    break;
                }
                //删除会话,返回删除会话的数量
                int deleteNum = Tools.deleteThreadById(ctx, threadId);
                if(deleteNum == 1){
                    //通知进度条改变,进度增加1
                    proDlg.incrementProgressBy(1);
                }
            }

            isCancleDeleteMessage = false;
            //清空集合
            selectItemSet.clear();
            //关闭进度对话框
            proDlg.dismiss();
            //刷新状态 在子线程刷新状态，会抛异常
            //flushState();

        }

    }


    /**
     * 响应listView条目的长按事件
     */
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        Cursor cursor = adapter.getCursor();
        cursor.moveToPosition(position);
        int threadId = cursor.getInt(INDEX_THREAD_ID);
        showAddToThreadGroupDialog(threadId);
        return true;
    }

    /**
     * 显示添加至群组的对话框
     * @param threadId  要添加的会话ID
     */
    private void showAddToThreadGroupDialog(final int threadId) {

        //获得所有的会话信息
        DbUtils dBUtils = DbUtils.getInstance(ctx);
        Cursor cursor = dBUtils.getAllGroup();
        if(cursor.getCount()>0){//说明已经有群组了
            //准备数据
            final int[] groupIds = new int[cursor.getCount()];
            String[] groupnames = new String[cursor.getCount()];

            while(cursor.moveToNext()){
                groupIds[cursor.getPosition()] = cursor.getInt(cursor.getColumnIndex("_id"));//获得群组ID
                groupnames[cursor.getPosition()] = cursor.getString(cursor.getColumnIndex("name"));
            }
            cursor.close();

            //弹出对话框
            AlertDialog.Builder adb = new AlertDialog.Builder(ctx);
            adb.setTitle("请选择要加入的群组");
            adb.setItems(groupnames, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //选择的群组的ID值为
                    int selectGroupId = groupIds[which];
                    //将会话ID与对应的群组ID，添加至，会话群组对应关系表
                    addThreadGroupValue(threadId,selectGroupId);
                    dialog.dismiss();
                }
            });

            adb.show();

        }else{//还没有群组
            Toast.makeText(ctx, "还没有创建群组", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 将会话ID与对应的群组ID，添加至，会话群组对应关系表
     * @param threadId  会话ID
     * @param selectGroupId  群组ID
     */
    protected void addThreadGroupValue(int threadId, int selectGroupId) {
        DbUtils dbUtils = DbUtils.getInstance(ctx);
        dbUtils.addThreadGroupValue(threadId,selectGroupId);

    }

}
